package com.cc.moxingvoice.lock;

import android.app.Dialog;
import android.content.Context;
import android.databinding.ViewDataBinding;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.cc.moxingvoice.BR;
import com.cc.moxingvoice.R;
import com.cc.moxingvoice.base.BaseLock;
import com.cc.moxingvoice.constant.LocalPath;
import com.cc.moxingvoice.databinding.ActivityVoiceBinding;
import com.cc.moxingvoice.databinding.ItemVoiceBinding;
import com.cc.moxingvoice.model.SingleTextItem;
import com.cc.moxingvoice.model.VoiceItem;
import com.cc.moxingvoice.ui.voice.AddVoiceActivity;
import com.cc.moxingvoice.ui.voice.ChangeVoiceActivity;
import com.cc.moxingvoice.ui.voice.RecordActivity;
import com.cc.moxingvoice.ui.voice.TtsActivity;
import com.cc.moxingvoice.ui.voice.VoiceAdapter;
import com.cc.moxingvoice.utils.FilesUtil;
import com.cc.moxingvoice.widget.dialog.ButtonTwoDialog;
import com.cc.moxingvoice.widget.dialog.ButtonTwoEditDialog;
import com.cc.moxingvoice.widget.dialog.ButtonTwoListDialog;
import com.mob.analysdk.AnalySDK;
import com.smp.soundtouchandroid.SoundStreamAudioPlayer;
import com.superc.cframework.base.ui.CBaseRecyclerViewAdapter;
import com.superc.cframework.utils.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 创建日期：2018/2/24 on 9:35
 * 描述：
 * 作者：郭士超
 * QQ：1169380200
 */

public class VoiceLock extends BaseLock<ActivityVoiceBinding> {

    private List<VoiceItem> mList;
    private VoiceAdapter mAdapter;

    private List<SingleTextItem> mLabelList;

    private RecyclerView mLabelRv;

    private MediaPlayer mp;//mediaPlayer对象
    private boolean play = false;//是否在播放
    private int playTag = -1;

    private float tempo = 1.0f;//卧槽，这个是速度啊，1.0表示正常设置新的速度控制值，
    private float pitchSemi = 1.0f;//卧槽，这个是音调，1.0表示正常，
    private float rate = 1.0f;//这个参数是变速又变声的，这个参数大于0，否则会报错
    private SoundStreamAudioPlayer player;

    private boolean flagManage;
    private boolean addTypeShow;

    public VoiceLock(Context context, ActivityVoiceBinding binding) {
        super(context, binding);
    }

    public VoiceLock(Context context, ActivityVoiceBinding binding, Bundle bundle) {
        super(context, binding, bundle);
    }

    @Override
    protected void init() {
        mBinding.llChange.setVisibility(View.GONE);
        mBinding.llAddType.setVisibility(View.GONE);

        initList();
        initMediaPlayer();

        addVoice();

        mobAnalysis();

        //把声音开最大
//        AudioUtil.soundMax(getContext());
    }

    public void refreshList() {
        // 添加音效到列表
        addVoice();
        setManage();
    }

    public boolean appBarRightManage() {
        if (!mBundle.getBoolean("manage")) {
            showToast("此文件不可管理");
            return flagManage;
        }
        flagManage = !flagManage;
        setManage();
        return flagManage;
    }

    private void setManage() {
        for (VoiceItem item : mList) {
            item.setManage(flagManage);
            item.notifyChange();
        }
        if (flagManage) {
            mBinding.llChange.setVisibility(View.VISIBLE);
            mBinding.tvAdd.setVisibility(View.GONE);
        } else {
            mBinding.llChange.setVisibility(View.GONE);
            mBinding.tvAdd.setVisibility(View.VISIBLE);
        }
    }

    public void addLocal(View view) {
        toAddVoiceActivity(AddVoiceLock.LOCAL);
    }

    public void addMo(View view) {
        toAddVoiceActivity(AddVoiceLock.MO);
    }

    public void addQQD(View view) {
        toAddVoiceActivity(AddVoiceLock.QQD);
    }

    public void addQQ(View view) {
        toAddVoiceActivity(AddVoiceLock.QQ);
    }

    public void addWX(View view) {
        toAddVoiceActivity(AddVoiceLock.WX);
    }

    public void addTts(View view) {
        Bundle bundle = new Bundle();
        bundle.putString("title", mBundle.getString("title"));
        startActivity(TtsActivity.class, bundle);
        mBinding.llAddType.setVisibility(View.GONE);
        mBinding.tvAdd.setText(R.string.add);
        addTypeShow = false;
    }

    public void addRecord(View view) {
        Bundle bundle = new Bundle();
        bundle.putString("title", mBundle.getString("title"));
        startActivity(RecordActivity.class);
        mBinding.llAddType.setVisibility(View.GONE);
        mBinding.tvAdd.setText(R.string.add);
        addTypeShow = false;
    }

    private void toAddVoiceActivity(int type) {
        Bundle bundle = new Bundle();
        bundle.putString("title", mBundle.getString("title"));
        bundle.putInt("type", type);
        startActivity(AddVoiceActivity.class, bundle);
        mBinding.llAddType.setVisibility(View.GONE);
        mBinding.tvAdd.setText(R.string.add);
        addTypeShow = false;
    }

    public void add(View view) {
        // 显示启动按钮
        if (addTypeShow) {
            mBinding.llAddType.setVisibility(View.GONE);
            mBinding.tvAdd.setText(R.string.add);
        } else {
            mBinding.llAddType.setVisibility(View.VISIBLE);
            mBinding.tvAdd.setText(R.string.cancel);
        }
        addTypeShow = !addTypeShow;
    }

    public void hideStartType() {
        if (addTypeShow) {
            mBinding.llAddType.setVisibility(View.GONE);
            addTypeShow = false;
            mBinding.tvAdd.setText(R.string.start);
        }
    }

    public void label(View view) {
        if (!isSelect()) {
            showToast(mContext.getString(R.string.least_one_choice));
            return;
        }
        new ButtonTwoListDialog(getContext(), R.style.dialog, mLabelList, new ButtonTwoListDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm, int position) {
                if (confirm) {
                    String newPath = "";
                    if (position == ButtonTwoListDialog.BUTTON) {
                        // 去删除标签
                        newPath = LocalPath.VOICE_PATH + mBundle.getString("title") + "/";
                    } else {
                        // 去修改标签
                        newPath = LocalPath.VOICE_PATH + mBundle.getString("title") + "/" + mLabelList.get(position).getText() + "/";
                    }
                    voiceLabel(newPath);
                }
                dialog.dismiss();
            }
        }).setTitle(mContext.getString(R.string.agree_revise)).setPositiveButton(mContext.getString(R.string.delete_label)).show();
    }

    private void voiceLabel(String newPath) {
        for (VoiceItem item : mList) {
            if (item.isCheck()) {
                // 移动
                if (!item.getPath().equals(newPath)) {
                    FilesUtil.mkdirPath(newPath);
                    FilesUtil.copyFile(item.getVoice(), newPath + item.getName());
                    FilesUtil.delete(item.getVoice());
                }
            }
        }
        initVoiceList();
    }

    public void delete(View view) {
        if (!isSelect()) {
            showToast(mContext.getString(R.string.least_one_choice));
            return;
        }
        new ButtonTwoDialog(getContext(), R.style.dialog, mContext.getString(R.string.are_you_sure_to_delete_this_voices), new ButtonTwoDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    voiceDelete();
                    dialog.dismiss();
                }
            }
        }).setTitle(mContext.getString(R.string.delete)).show();
    }

    private void voiceDelete() {
        for (VoiceItem item : mList) {
            if (item.isCheck()) {
                FilesUtil.delete(item.getVoice());
            }
        }
        initVoiceList();
    }

    public void rename(View view) {
        if (!isSelect()) {
            showToast(mContext.getString(R.string.least_one_choice));
            return;
        }
        new ButtonTwoEditDialog(getContext(), R.style.dialog, new ButtonTwoEditDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm, String content) {
                if (confirm) {
                    if (content.isEmpty()) {
                        ToastUtil.showShort(getContext(), mContext.getString(R.string.input_label_null));
                        return;
                    }
                    voiceRename(content);
                    dialog.dismiss();
                }
            }
        }).setHint(mContext.getString(R.string.fill_new_name)).setTitle(mContext.getString(R.string.hint)).show();
    }

    private void voiceRename(String name) {
        int error = 0;
        for (VoiceItem item : mList) {
            if (item.isCheck()) {
                String extension = FilesUtil.getFileName(FilesUtil.getFileNameHandExtension(item.getVoice()))[1];
                if (extension == null || extension.isEmpty()) {
                    showToast("重命名失败");
                    return;
                }
                String newName = name + "." + extension;
                if (!FilesUtil.fileRename(item.getVoice(), newName, true)) { // 如果重命名失败
                    error++;
                }
            }
        }
        if (error != 0) {
            showToast("重命名失败" + error + "个");
        }
        initVoiceList();
    }

    private void initVoiceList() {
        addVoice();
        for (VoiceItem item : mList) {
            item.setManage(true);
        }
    }

    private boolean isSelect() {
        for (VoiceItem item : mList) {
            if (item.isCheck()) {
                return true;
            }
        }
        return false;
    }

    private void mobAnalysis() {
        HashMap<String, Object> eventParams = new HashMap<String, Object>();
        eventParams.put("page", "Voice Page");
        AnalySDK.trackEvent("page-jump", eventParams);
    }

    private void initMediaPlayer() {
        mp = new MediaPlayer();
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer arg0) {
                // TODO Auto-generated method stub
                play = false;
            }
        });
    }

    private void initList() {
        mList = new ArrayList<VoiceItem>();
        LinearLayoutManager ms = new LinearLayoutManager(mContext);
        mBinding.rvVoice.setLayoutManager(ms);
        mAdapter = new VoiceAdapter(mContext, mList, R.layout.item_voice, BR.item);
        mBinding.rvVoice.setAdapter(mAdapter); // 这里或者在xml里设置adapter
        mAdapter.setOnItemClickListener(new CBaseRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(ViewDataBinding binding, int position) {
                if (flagManage) {
                    mList.get(position).setCheck(!mList.get(position).isCheck());
                    ((ItemVoiceBinding) binding).check.setChecked(mList.get(position).isCheck());
                    return;
                }
                playVoice(position);

                HashMap<String, Object> eventParams = new HashMap<String, Object>();
                eventParams.put("voice-type", "Activity");
                AnalySDK.trackEvent("play-voice", eventParams);
            }
        });

        mLabelList = new ArrayList<>();
    }

    public static byte[] File2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * 播放本地音频
     *
     * @param position
     */
    private void playVoice(int position) {
        if (play && playTag == position) {
            mp.stop();
            play = false;
        } else {
            try {
                if (mp != null) {
                    mp.reset();
                }
                Uri uri = Uri.parse(mList.get(position).getVoice());
                mp = MediaPlayer.create(getContext(), uri);//重新设置要播放的音频
                mp.start();//开始播放
                play = true;
            } catch (Exception e) {
                e.printStackTrace();//输出异常信息
            }
        }
        playTag = position;
    }

    public void onDestroy() {
        if (mp == null) {
            return;
        }
        if (mp.isPlaying()) {
            mp.stop();
        }
        mp.release();//释放资源
    }

    /**
     * 添加本地音频到列表
     */
    private void addVoice() {
        mList.clear();

        String voicePath = LocalPath.VOICE_PATH + mBundle.getString("title") + "/";
        List<String> voiceList = FilesUtil.getVoiceFileName(voicePath);
        int id = 0;
        for (String voice : voiceList) {
            id++;
            mList.add(new VoiceItem(id + "", id + "", voice, voicePath + voice, voicePath, mContext.getString(R.string.no_label)));
        }

        mLabelList.clear();
        mLabelList.add(new SingleTextItem(mContext.getString(R.string.add_new_label)));
        List<String> labelList = FilesUtil.getFolderName(voicePath);
        for (String label : labelList) {
            String voiceLabelPath = voicePath + label + "/";
            List<String> voiceLabelList = FilesUtil.getVoiceFileName(voiceLabelPath);
            if (voiceLabelList.size() > 0) {
                for (String voice : voiceLabelList) {
                    id++;
                    mList.add(new VoiceItem(id + "", id + "", voice, voiceLabelPath + voice, voiceLabelPath, label));
                }
                mLabelList.add(new SingleTextItem(label));
            } else {
                // 标签下没东西就删了
                FilesUtil.delete(voiceLabelPath);
            }
        }

        mAdapter.notifyDataSetChanged(); // 刷新数据
    }

    public CBaseRecyclerViewAdapter getAdapter() {
        return mAdapter;
    }

    public boolean isFlagManage() {
        return flagManage;
    }

    public void setFlagManage(boolean flagManage) {
        this.flagManage = flagManage;
    }

}
